package com.strawcom.charmring.ui;

import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.os.Handler;
import android.text.Editable;
import android.text.InputType;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import com.android.volley.Request.Method;
import com.strawcom.charmring.App;
import com.strawcom.charmring.BaseActivity;
import com.strawcom.charmring.C;
import com.strawcom.charmring.R;
import com.strawcom.charmring.bean.UserInfo;
import com.strawcom.charmring.bean.http.BaseResponse;
import com.strawcom.charmring.util.HttpUtil;
import com.strawcom.charmring.util.HttpUtil.ResponeListener;
import com.strawcom.charmring.util.PreferenceUtil;
import com.strawcom.charmring.view.CustomProgressDialog;
import com.strawcom.charmring.view.TitleView;
import org.kymjs.kjframe.utils.SystemTool;

/**
 *
 * @ClassName: RegisterActivity
 * @Description:注册activity
 * @author liyongqiang
 * @date 2015-3-30 下午11:47:52
 *
 */
public class RegisterActivity extends BaseActivity implements OnClickListener {

	private TitleView textView;
	private EditText editPhone, editPwd, editAuthCode;
	private Button btnRegister;
	private TextView tvCodeTip;
	private boolean isRegister;
	private CustomProgressDialog dialog ;
	private static final int msg_get_code=1;
	private int time=60;
	private TextView mCountryText;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		setContentView(R.layout.activity_register);
		super.onCreate(savedInstanceState);
		initViews();

		findViewById(R.id.layout_content).setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				closeInputMethod();
			}
		});
	}

	private void initViews() {
		textView = (TitleView) findViewById(R.id.title_view);
		textView.setTitleText(R.string.register_title);
		editPhone = (EditText) findViewById(R.id.edit_number);
		editPwd = (EditText) findViewById(R.id.edit_pwd);
		editAuthCode = (EditText) findViewById(R.id.edit_code);
		btnRegister = (Button) findViewById(R.id.btn_register);
		tvCodeTip = (TextView) findViewById(R.id.tv_code_tip);
		btnRegister.setOnClickListener(this);
		editAuthCode.setInputType(InputType.TYPE_NULL);

		mCountryText = (TextView) findViewById(R.id.country_text);

		mCountryText.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				final CharSequence[] charSequences = getResources().getStringArray(R.array.country_spinner);
				AlertDialog.Builder builder = new AlertDialog.Builder(RegisterActivity.this);

				builder.setTitle("选择国家编号")
						.setIcon(R.drawable.ic_launcher)
						.setItems(charSequences, new DialogInterface.OnClickListener() {

                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                Toast.makeText(RegisterActivity.this, charSequences[which], Toast.LENGTH_SHORT).show();
                                Log.i("abc", "i" + which);
                                mCountryText.setText(charSequences[which]);
                            }
                        }).show();
			}
		});
		dialog= CustomProgressDialog.createDialog(this, false);
		editAuthCode.addTextChangedListener(new TextWatcher() {

			@Override
			public void onTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) {
				if(time>0){
					isRegister=true;
					btnRegister.setText(R.string.register);
				}
			}

			@Override
			public void beforeTextChanged(CharSequence arg0, int arg1, int arg2,
					int arg3) {

			}

			@Override
			public void afterTextChanged(Editable arg0) {

			}
		});
	}

	private UserInfo checkRegister() {
		UserInfo userInfo = new UserInfo();
		Editable mobile = editPhone.getText();
		if (TextUtils.isEmpty(mobile)) {
			editPhone.setHint(R.string.phone_null);
			return null;
		} else {
			if (mobile.length() == 11||isOtherCountry()) {
				StringBuffer stringBuffer = new StringBuffer(mCountryText.getText());
				String countryText = stringBuffer.deleteCharAt(0).toString();
				userInfo.setPhone(countryText+mobile.toString());
				System.out.println(userInfo.getPhone().toString());
			} else {
				editPhone.setText("");
				editPhone.setHint(R.string.phone_format);
				return null;
			}
		}

		Editable pwd = editPwd.getText();
		if (TextUtils.isEmpty(pwd)) {
			editPwd.setHint(R.string.pwd_null);
			return null;
		} else {
			if (editPwd.getText().toString().trim().length() < 6
					|| editPwd.getText().toString().trim().length() > 16) {
				editPwd.setText("");
				editPwd.setHint(R.string.pwd_format);
				return null;
			} else {
				String password = editPwd.getText().toString().trim();
				userInfo.setPassword(password);
			}
		}

		if(isRegister){
			Editable code = editAuthCode.getText();
			if(TextUtils.isEmpty(code)){
				editAuthCode.setHint(R.string.code_null);
				return null;
			}else if(code.toString().trim().length()!=6){
				editAuthCode.setText("");
				editAuthCode.setHint(R.string.code_format);
				return null;
			}else{
				userInfo.setPhoneauth(code.toString().trim());
				userInfo.setAppversion(SystemTool.getAppVersion(this));
				userInfo.setPhoneversion(SystemTool.getSystemVersion());
			}
		}

		return userInfo;
	}

	@SuppressLint("HandlerLeak")
	Handler mHandler=new Handler(){
		public void handleMessage(android.os.Message msg) {
			switch (msg.what) {
			case msg_get_code:
				if(time>0){
					tvCodeTip.setText(String.format(getString(R.string.auth_code_tip), --time));
					sendEmptyMessageDelayed(msg_get_code, 1000);
				}else{
					editAuthCode.setInputType(InputType.TYPE_NULL);
					editAuthCode.setBackgroundResource(R.drawable.border_edit_unuse);
					editAuthCode.setText("");
					isRegister=false;
					btnRegister.setText(R.string.re_send_code);
				}
				break;

			default:
				break;
			}
		};
	};

	private void getAuthCode(final UserInfo info) {


		dialog.setMessage(R.string.wating_get_auth_code);
		dialog.show();
		info.msgid = C.request_msgid_post_user_regist;
		HttpUtil.requestJson(Method.POST,info, new ResponeListener() {

			@Override
			public void onResponse(BaseResponse response,String resultStr) {
				dialog.dismiss();
				if(response.retcode==1){
					showRegister();
				} else if(response.retcode==105){
					showToast(R.string.register_error_105);
				} else {
					showToast(R.string.get_auth_code_error);
				}
			}

			@Override
			public void onErrorResponse(Exception error) {
				dialog.dismiss();
					if (SystemTool.checkNet(RegisterActivity.this)) {
						showToast(R.string.get_auth_code_error);
					} else {
						showToast(R.string.net_error);
					}
			}
		});
	}

	private void showRegister(){
		tvCodeTip.setText(String.format(getString(R.string.auth_code_tip),time));
		tvCodeTip.setVisibility(View.VISIBLE);
		editAuthCode.setInputType(InputType.TYPE_CLASS_PHONE);
		editAuthCode.setBackgroundResource(R.drawable.border_edit);
		btnRegister.setText(R.string.re_send_code);
		mHandler.sendEmptyMessageDelayed(msg_get_code, 1000);
	}

	private void register(final UserInfo info){

		dialog.setMessage(R.string.wating_register);
		dialog.show();
		info.msgid = C.request_msgid_post_user_regist;
		HttpUtil.requestJson(Method.POST, info, new ResponeListener() {

			@Override
			public void onResponse(BaseResponse response, String resultStr) {
				dialog.dismiss();
				if (isOtherCountry()) {
					response.retcode = 0;
				}
				registerResult(response.retcode);
			}

			@Override
			public void onErrorResponse(Exception error) {
				dialog.dismiss();
				if (SystemTool.checkNet(RegisterActivity.this)) {
					showToast(R.string.request_error);
				} else {
					showToast(R.string.net_error);
				}
			}
		});
	}

	private void storeDefaultProperties(){
		PreferenceUtil.write(this, C.sp.switch_phone_calls_reminding, true);
		PreferenceUtil.write(this, C.sp.switch_location_alarm, true);
		PreferenceUtil.write(this, C.sp.switch_mobile_lost_proof, true);
		PreferenceUtil.write(this, C.sp.switch_phone_calls_reminding, true);
		PreferenceUtil.write(this, C.sp.switch_light_open, true);
		PreferenceUtil.write(this, C.sp.switch_light_time, C.app.default_ble_light_time);
	}

	private void storeUserInfo(String phone,String password){
		StringBuffer stringBuffer = new StringBuffer(mCountryText.getText());
		String countryText = stringBuffer.deleteCharAt(0).toString();

        PreferenceUtil.write(this, C.sp.phone, phone);
		PreferenceUtil.write(this, C.sp.password, password);
		PreferenceUtil.write(this, C.sp.phone_ex, countryText);
	}

	private void storeRegisterInfo(String phone,String password) {
		storeUserInfo(phone, password);
		storeDefaultProperties();
	}

	private void registerResult(int retcode){
		if(retcode==0){
			showToast(R.string.register_success);
			/**Edit**/
			StringBuffer stringBuffer = new StringBuffer(mCountryText.getText());
			String countryText = stringBuffer.deleteCharAt(0).toString();
			String phone = countryText + editPhone.getText().toString().trim();
			/**Edit**/
			String password = editPwd.getText().toString().trim();
			storeRegisterInfo(phone, password);
			App.i().getDailySummary(true); // init

			actionStart(MainActivity.class);
			finish();
		}else{
			editAuthCode.setText("");
			editAuthCode.setInputType(InputType.TYPE_NULL);
			editAuthCode.setBackgroundResource(R.drawable.border_edit_unuse);
			isRegister=false;
			btnRegister.setText(R.string.re_send_code);
			if(retcode == 105) {
				showToast(R.string.register_error_105);
			} else if (retcode == 106) {
				showToast(R.string.register_error_106);

			}
		}
	}

	@Override
	public void onClick(View view) {
		switch (view.getId()) {
		case R.id.btn_register:
			UserInfo info = checkRegister();
			if (info != null && !isRegister) {
				time=60;
				mHandler.removeMessages(msg_get_code);
				tvCodeTip.setVisibility(View.GONE);
				getAuthCode(info);
			} else if (info != null && isRegister) {
				mHandler.removeMessages(msg_get_code);
				tvCodeTip.setVisibility(View.GONE);
				register(info);
			}
			break;
		default:
			break;
		}
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
		mHandler.removeMessages(msg_get_code);
	}

	private boolean isOtherCountry() {
		return !mCountryText.getText().equals("+86");
	}
}
